use std::fmt::Debug;
use std::time::Duration;
use std::sync::Arc;
use rand::{Rng, thread_rng};
use hex;

/// 跟踪上下文
#[derive(Debug, Clone)]
pub struct SpanContext {
    /// 跟踪ID
    pub trace_id: String,
    /// 跨度ID
    pub span_id: String,
    /// 父跨度ID
    pub parent_span_id: Option<String>,
    /// 采样标志
    pub sampled: bool,
}

impl SpanContext {
    /// 创建新的根跟踪上下文
    pub fn new_root(sampled: bool) -> Self {
        Self {
            trace_id: generate_id(),
            span_id: generate_id(),
            parent_span_id: None,
            sampled,
        }
    }
    
    /// 创建子跨度上下文
    pub fn new_child(&self) -> Self {
        Self {
            trace_id: self.trace_id.clone(),
            span_id: generate_id(),
            parent_span_id: Some(self.span_id.clone()),
            sampled: self.sampled,
        }
    }
    
    /// 判断是否为根跨度
    pub fn is_root(&self) -> bool {
        self.parent_span_id.is_none()
    }
}

/// 跨度接口
pub trait Span: Send + Sync + 'static {
    /// 添加属性
    fn add_attribute(&self, key: &str, value: &str);
    
    /// 添加事件
    fn add_event(&self, name: &str, attributes: &[(&str, &str)]);
    
    /// 设置状态
    fn set_status(&self, status: SpanStatus, description: Option<&str>);
    
    /// 结束跨度
    fn end(&self, duration: Option<Duration>);
    
    /// 获取上下文
    fn context(&self) -> &SpanContext;
}

/// 跟踪器接口
pub trait Tracer: Send + Sync + 'static {
    /// 创建跨度
    fn create_span(&self, name: &str, context: Option<SpanContext>) -> Box<dyn Span>;
    
    /// 开始跨度
    fn start_span(&self, name: &str, context: Option<SpanContext>) -> (Box<dyn Span>, SpanContext);
    
    /// 结束跨度
    fn end_span(&self, context: SpanContext, duration: Option<Duration>);
    
    /// 设置全局跟踪状态
    fn set_global_attributes(&self, attributes: &[(&str, &str)]);
}

/// 跨度状态
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SpanStatus {
    /// 未设置
    Unset,
    /// 正常
    Ok,
    /// 错误
    Error,
}

/// 内存跟踪器实现
pub struct MemoryTracer {
    /// 全局属性
    global_attributes: parking_lot::RwLock<Vec<(String, String)>>,
    /// 活动跨度
    active_spans: dashmap::DashMap<String, Arc<MemorySpan>>,
}

impl MemoryTracer {
    /// 创建新的内存跟踪器
    pub fn new() -> Self {
        Self {
            global_attributes: parking_lot::RwLock::new(Vec::new()),
            active_spans: dashmap::DashMap::new(),
        }
    }
}

impl Default for MemoryTracer {
    fn default() -> Self {
        Self::new()
    }
}

impl Clone for MemoryTracer {
    fn clone(&self) -> Self {
        Self {
            global_attributes: parking_lot::RwLock::new(self.global_attributes.read().clone()),
            active_spans: dashmap::DashMap::new(),
        }
    }
}

impl Tracer for MemoryTracer {
    fn create_span(&self, name: &str, context: Option<SpanContext>) -> Box<dyn Span> {
        let context = context.unwrap_or_else(|| SpanContext::new_root(true));
        let span = Arc::new(MemorySpan::new(name, context.clone()));
        self.active_spans.insert(context.span_id.clone(), span.clone());
        
        // 创建一个可以转换为Box<dyn Span>的SpanWrapper
        Box::new(SpanWrapper(span))
    }
    
    fn start_span(&self, name: &str, context: Option<SpanContext>) -> (Box<dyn Span>, SpanContext) {
        let ctx = context.unwrap_or_else(|| SpanContext::new_root(true));
        let span = self.create_span(name, Some(ctx.clone()));
        (span, ctx)
    }
    
    fn end_span(&self, context: SpanContext, duration: Option<Duration>) {
        if let Some(span) = self.active_spans.remove(&context.span_id) {
            span.1.end(duration);
        }
    }
    
    fn set_global_attributes(&self, attributes: &[(&str, &str)]) {
        let mut attr_lock = self.global_attributes.write();
        attr_lock.clear();
        for (key, value) in attributes {
            attr_lock.push((key.to_string(), value.to_string()));
        }
    }
}

// Span包装器, 用来解决Arc<MemorySpan>不能转换为Box<dyn Span>的问题
struct SpanWrapper(Arc<MemorySpan>);

impl Span for SpanWrapper {
    fn add_attribute(&self, key: &str, value: &str) {
        self.0.add_attribute(key, value)
    }
    
    fn add_event(&self, name: &str, attributes: &[(&str, &str)]) {
        self.0.add_event(name, attributes)
    }
    
    fn set_status(&self, status: SpanStatus, description: Option<&str>) {
        self.0.set_status(status, description)
    }
    
    fn end(&self, duration: Option<Duration>) {
        self.0.end(duration)
    }
    
    fn context(&self) -> &SpanContext {
        self.0.context()
    }
}

/// 内存跨度实现
pub struct MemorySpan {
    /// 名称
    name: String,
    /// 上下文
    context: SpanContext,
    /// 属性
    attributes: parking_lot::RwLock<Vec<(String, String)>>,
    /// 事件
    events: parking_lot::RwLock<Vec<SpanEvent>>,
    /// 状态
    status: parking_lot::RwLock<(SpanStatus, Option<String>)>,
    /// 结束标志
    ended: std::sync::atomic::AtomicBool,
    /// 创建时间
    created_at: std::time::Instant,
}

impl MemorySpan {
    /// 创建新的内存跨度
    pub fn new(name: &str, context: SpanContext) -> Self {
        Self {
            name: name.to_string(),
            context,
            attributes: parking_lot::RwLock::new(Vec::new()),
            events: parking_lot::RwLock::new(Vec::new()),
            status: parking_lot::RwLock::new((SpanStatus::Unset, None)),
            ended: std::sync::atomic::AtomicBool::new(false),
            created_at: std::time::Instant::now(),
        }
    }
    
    /// 检查跨度是否已结束
    fn is_ended(&self) -> bool {
        self.ended.load(std::sync::atomic::Ordering::Relaxed)
    }
}

impl Span for MemorySpan {
    fn add_attribute(&self, key: &str, value: &str) {
        if self.is_ended() {
            return;
        }
        
        let mut attrs = self.attributes.write();
        attrs.push((key.to_string(), value.to_string()));
    }
    
    fn add_event(&self, name: &str, attributes: &[(&str, &str)]) {
        if self.is_ended() {
            return;
        }
        
        let event = SpanEvent {
            name: name.to_string(),
            timestamp: std::time::SystemTime::now(),
            attributes: attributes.iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
        };
        
        let mut events = self.events.write();
        events.push(event);
    }
    
    fn set_status(&self, status: SpanStatus, description: Option<&str>) {
        if self.is_ended() {
            return;
        }
        
        let mut status_lock = self.status.write();
        *status_lock = (status, description.map(|s| s.to_string()));
    }
    
    fn end(&self, duration: Option<Duration>) {
        if self.is_ended() {
            return;
        }
        
        self.ended.store(true, std::sync::atomic::Ordering::Relaxed);
    }
    
    fn context(&self) -> &SpanContext {
        &self.context
    }
}

/// 跨度事件
#[derive(Debug, Clone)]
struct SpanEvent {
    /// 名称
    name: String,
    /// 时间戳
    timestamp: std::time::SystemTime,
    /// 属性
    attributes: Vec<(String, String)>,
}

// 生成随机ID
fn generate_id() -> String {
    let mut rng = thread_rng();
    let mut bytes = [0u8; 8];
    rng.fill(&mut bytes);
    
    hex::encode(bytes)
} 